package server

import (
	"cmp"
	"net/http"
	"server/internal/core/config"
	"server/internal/core/constant"
	"server/internal/core/logger"
	"time"

	"github.com/gin-gonic/gin"
)

type server struct {
	*http.Server
	router *gin.Engine
	config *config.ServerConfig
}

var _server *server

// Init 初始化server
func Init() error {
	router := gin.New()
	config := config.Server

	// 使用日志和恢复中间件
	router.Use(Logger(logger.Logger))
	router.Use(Recover(logger.Logger))

	// 健康检查
	router.GET("/health", healthCheck)

	// 设置gin模式
	gin.SetMode(cmp.Or(config.Mode, gin.ReleaseMode))

	// 初始化server
	_server = &server{
		Server: &http.Server{
			Addr:         config.Addr,
			Handler:      router,
			ReadTimeout:  cmp.Or(config.ReadTimeout, 5*time.Second),
			WriteTimeout: cmp.Or(config.WriteTimeout, 10*time.Second),
			IdleTimeout:  cmp.Or(config.IdleTimeout, 60*time.Second),
		},
		router: router,
		config: config,
	}
	return nil
}

// 健康检查
func healthCheck(c *gin.Context) {
	c.JSON(http.StatusOK, &ResponseData{
		Code:    0,
		Message: "success",
		Data:    nil,
		TraceID: c.GetString(constant.TraceIDKeyType{}),
	})
}

// 启动server
func Run() error {
	logger.Logger.Info("server is running", "addr", _server.Addr)
	return _server.ListenAndServe()
}

// 获取router
func GetRouter() *gin.Engine {
	return _server.router
}
